package dbOperation;

import library.Book;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * Created by v on 17-5-18.
 */
public class DbSelect {
    /**
     * 返回总的书本条目数
     * @return 图书馆的书本条目数
     */
    public static int amount(){
        Statement st=DbConnection.getStatment();
        try {
            ResultSet rs=st.executeQuery("SELECT amount FROM amount;");
            if(rs.next()){
                return rs.getInt(1);
            }else {
                return -1;
            }
        }catch (SQLException ex){
            return -1;
        }
    }

    /**
     * 通过页码数查找一个页面所有的书
     * @param page 页码数
     * @return 一个页面所有的书
     */
    public static List<Book> books(int page){
        List<Book> list=new LinkedList<>();
        //根据第几页算出初始下标
        page=(page-1)*10;

        try {
            String sql="SELECT * FROM library LIMIT "+page+",10;";
            Statement st=DbConnection.getStatment();
            ResultSet rs=st.executeQuery(sql);
            while (rs.next()){
                Book book=new Book();
                book.setId(rs.getInt(1));
                book.setName(rs.getString(2));
                book.setPrice(rs.getDouble(3));
                book.setAmount(rs.getInt(4));
                book.setAuthor(rs.getString(5));
                list.add(book);
            }
        }catch (SQLException ex){
            ex.printStackTrace();
        }

        return list;
    }

    public static void main(String[] args) {
        List<Book> list=DbSelect.books(1);
        for (Book book:list){
            System.out.println(book.getName());
        }
    }
}
